<template>
  <div class="home-category-goods">
    <MyPanel :title="categoryTitle" :subTitle="categorySubTitle">
      <ul v-if="goods.length" class="goods-list">
        <li class="item" v-for="item in goods" :key="item.productId">
          <div class="goods-container">
            <!-- 商品图片 -->
            <div class="goods-image">
              <img :src="item.imageUrl" :alt="item.productName" />
            </div>
            
            <!-- 商品名称 -->
            <div class="goods-name ellipsis">{{ item.productName }}</div>
            
            <!-- 价格和购物车按钮 -->
            <div class="goods-price">
              <span class="price">￥{{ item.price }}</span>
              <div class="add-cart-btn" @click="addToCart(item)">
                <span>+</span>
              </div>
            </div>
            
            <!-- 购买按钮 -->
            <div class="buy-btn">
              <button class="purchase-btn" @click="buyNow(item)">立即购买</button>
            </div>
          </div>
        </li>
      </ul>
      
      <!-- 骨架屏 -->
      <div v-else class="goods-list skeleton-list">
        <el-skeleton v-for="i in 8" :key="i" style="width: 265px">
          <template #template>
            <el-skeleton-item variant="image" style="width: 240px; height: 240px" />
            <div style="padding: 14px">
              <el-skeleton-item variant="p" style="width: 50%" />
              <div
                style="
            display: flex;
            align-items: center;
            justify-items: space-between;
          "
              >
                <el-skeleton-item variant="text" style="margin-right: 16px" />
                <el-skeleton-item variant="text" style="width: 30%" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>
    </MyPanel>
  </div>
</template>

<script>
import { ref, onMounted, computed } from "vue";
import MyPanel from "@/components/MyPanel.vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

export default {
  components: {
    MyPanel
  },
  props: {
    // 获取商品的API函数
    fetchProducts: {
      type: Function,
      required: true
    },
    // 分类名称
    category: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const goods = ref([]);
    const router = useRouter();
    
    const fetchGoods = async () => {
      try {
        const res = await props.fetchProducts(props.category);
        
        if (res && res.code === 200 && Array.isArray(res.data)) {
          // 过滤掉status不为1（下架）的商品
          const filteredProducts = res.data.filter(item => item.status === 1);
          goods.value = filteredProducts;
        } else {
          goods.value = [];
        }
      } catch (error) {
        console.error(`获取${props.category}商品列表失败:`, error);
        goods.value = [];
      }
    };
    
    // 添加商品到购物车
    const addToCart = async (product) => {
      try {
        // 这里需要根据实际API调整
        // const res = await addProductToCart({
        //   productId: product.productId,
        //   quantity: 1
        // });
        
        ElMessage.success('商品已添加到购物车');
      } catch (error) {
        console.error("添加购物车失败:", error);
        ElMessage.error('添加购物车失败，请稍后重试');
      }
    };
    
    // 立即购买
    const buyNow = async (product) => {
      try {
        // 直接跳转到结算页面，并传递商品信息
        router.push({
          path: '/checkout',
          query: {
            productId: product.productId,
            productName: product.productName,
            price: product.price,
            imageUrl: product.imageUrl,
            quantity: 1
          }
        });
      } catch (error) {
        console.error("立即购买失败:", error);
        ElMessage.error('立即购买失败，请稍后重试');
      }
    };
    
    onMounted(() => {
      fetchGoods();
    });
    
    // 根据分类名称确定标题
    const categoryTitle = computed(() => {
      // 可以根据需要添加更多分类的标题映射
      const titleMap = {
        '居家': '居家',
        'car': '汽车用品',
        '美食': '美食',
        '服饰': '服饰',
        '运动': '运动',
        '个护': '个人护理',
        '严选': '严选',
        '数码': '数码',
        '杂货': '杂货'
      };
      return titleMap[props.category] || props.category;
    });
    
    // 根据分类名称确定子标题
    const categorySubTitle = computed(() => {
      return `精选${categoryTitle.value}好物`;
    });
    
    return { goods, addToCart, buyNow, categoryTitle, categorySubTitle };
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";
@import "@/assets/styles/mixins.less";

.home-category-goods {
  .goods-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 40px;
    
    .item {
      width: 265px;
      height: 365px;
      background-color: #f5f5f5;
      margin-bottom: 20px;
      position: relative;
      
      .goods-container {
        padding: 10px;
        text-align: center;
        
        .goods-image {
          width: 100%;
          height: 200px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }
        
        .goods-name {
          font-size: 16px;
          margin: 10px 0;
          height: 40px;
          line-height: 20px;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          margin-bottom: 10px;
          
          .price {
            font-size: 18px;
            color: @priceColor;
            font-weight: bold;
          }
          
          .add-cart-btn {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: @xtxColor;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            font-weight: bold;
          }
        }
        
        .buy-btn {
          .purchase-btn {
            width: 90%;
            height: 35px;
            background-color: @xtxColor;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            
            &:hover {
              background-color: #b8884d;
            }
          }
        }
      }
      
      .hoverShadow();
    }
  }
  
  .skeleton-list {
    .el-skeleton {
      margin-bottom: 20px;
    }
  }
}
</style>